package com.longge;

public class NumMatrix {

    private final int[][] preNum;

    public NumMatrix(int[][] matrix) {
        int m = matrix.length + 1;
        int n = matrix[0].length + 1;
        preNum = new int[m][n];
        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                preNum[i][j] = preNum[i - 1][j] + preNum[i][j - 1] + matrix[i - 1][j - 1] - preNum[i - 1][j - 1];
            }
        }
    }

    public int sumRegion(int row1, int col1, int row2, int col2) {

        return preNum[row2 + 1][col2 + 1] - preNum[row1][col2 + 1] - preNum[row2 + 1][col1] + preNum[row1][col1];
    }
}